const userList = [{
	user: 'admin',
	pwd: 'admin',
	nickname: '管理员人员',
},{
	user: 'qwertyu',
	pwd: '123',
	nickname: '张三三同学',
}]
const key = 'qweqwrq'
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
module.exports = {
	devServer: {
		before(app) {
			app.use(bodyParser.json())
			app.post('/api/login', (req, res) => {
				const { user, pwd } = req.body;
				const item = userList.find(v => v.user === user && pwd === v.pwd)
				if(item) {
					res.send({
						code:  200,
						data: {
							nickname: item.nickname
						},
						token: JWT.sign({ user, nickname: item.nickname }, key),
						message: '登录成功'
					})
				} else {
					res.send({
						code:  404,
						message: '账户密码错误， 请冲洗你输入'
					})
				}
			})

			app.post('/api/regist', (req, res) => {
				const { user } = req.body;
				if(userList.some(v => v.user === user)) {
					res.send({
						code: 403,
						message: '该账户已经被注册'
					})
				} else {
					userList.push(req.body)
					res.send({
						code: 200,
						message: '注册成功'
					})
				}
			})

			app.post('/api/user/modify', (req, res) => {
				const { pwd, nickname, token } = req.body;
				try {
					const user = JWT.verify(token, key);
					const currUser =userList.find(v => v.user === user.user)
					currUser.pwd = pwd
					currUser.nickname = nickname
	
					res.send({
						code: 200,
						message: '修改成功',
						token: JWT.sign({ user: user.user, nickname }, key),
					})
				} catch {
					res.send({
						code: 403, 
						message: '非法token，请登录'
					})
				}
			})
		}
	}
}